package com.liuanbang.saro.sarodemo.util;

import android.content.Context;

import com.liuanbang.saro.sarodemo.base.BaseActivity;

import java.util.Stack;


/**
 * activity堆栈控制工具
 */
public class ActivityUtil {

    private static Stack<BaseActivity> activityStack;

    /**
     * 添加Activity到堆栈
     */
    public static void addActivity(BaseActivity activity) {
        if (activityStack == null) {
            activityStack = new Stack<BaseActivity>();
        }
        activityStack.add(activity);
    }

    /**
     * 获取当前Activity(堆栈中最后一个压入的)
     */
    public static BaseActivity currentActivity() {
        return activityStack.lastElement();
    }

    /**
     * 结束当前Activity(堆栈中最后一个压入的)
     */
    public static void finishActivity() {
        BaseActivity activity = activityStack.lastElement();
        if (activity != null && !activity.isFinishing()) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 结束指定的Activity
     */
    public static void finishActivity(BaseActivity activity) {
        if (activity != null && !activity.isFinishing()) {
            activityStack.remove(activity);
            activity.finish();
            activity = null;
        }
    }

    /**
     * 结束指定类名的Activity
     */
    public static void finishActivity(Class<?> cls) {
        for (BaseActivity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                finishActivity(activity);
            }
        }
    }

    /**
     * 退出应用程序
     */
    public static void AppExit(Context context) {
        android.app.ActivityManager activityMgr = (android.app.ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        activityMgr.killBackgroundProcesses(context.getPackageName());
    }

    /**
     * 结束所有Activity
     */
    public static void finishAllActivity(BaseActivity activity) {
        activityStack.removeAllElements();
        if (activity != null) {
            activityStack.add(activity);
        }
    }

    /**
     * 查看堆栈内是否存在指定的activity
     */
    public static boolean isExistActivity(Class<?> cls) {
        for (BaseActivity activity : activityStack) {
            if (activity.getClass().equals(cls)) {
                return true;
            }
        }
        return false;
    }
}
